import Vue from 'vue'

import 'normalize.css/normalize.css'// A modern alternative to CSS resets
import 'babel-polyfill'
import ElementUI from 'element-ui'
import 'element-ui/lib/theme-chalk/index.css'
import { Message } from 'element-ui';
// import locale from 'element-ui/lib/locale/lang/en' // lang i18n

import '@/styles/index.scss' // global css
import App from './App'
import router from './router'
import store from './store'

import i18n from './lang' // Internationalization
import '@/icons' // icon
// import '@/permission' // permission control
import NProgress from 'nprogress' // Progress 进度条
import 'nprogress/nprogress.css'// Progress 进度条样式

import { getPageAction } from '@/utils/auth'

import preview from 'vue-photo-preview'  // 图片预览
import 'vue-photo-preview/dist/skin.css'
Vue.use(preview)

Vue.use(ElementUI, {
  size: 'medium', // set element-ui default size
  i18n: (key, value) => i18n.t(key, value)
})

// Vue.use(ElementUI, { locale })
Vue.prototype.$message = Message

Vue.config.productionTip = false

router.beforeEach((to, from, next) => {
  if (to.matched.some(route => route.meta.requireAuth)) {
    NProgress.start()
    if (store.getters.token) {
      if (to.path === '/login') {
        next({ path: '/' })
        NProgress.done()
      } else {
        if (!store.getters.userId) {
          store.dispatch('GetInfo').then(res => { // 拉取用户信息,如果用户为空，则身份认证失败，直接登出
            NProgress.done()
            if (+res.code === -1) {
              next({ path: '/login' })
            } else {
              next()
            }
          }).catch((err) => {
            store.dispatch('FedLogOut').then(() => {
              ElementUI.Message.error(err || '身份认证失败，请重新登录')
              next({ path: '/' })
            })
          })
        } else {
          next()
          NProgress.done()
        }
      }
    } else {
      next({ path: '/login' })
      NProgress.done()
    }
  } else {
    next()
  }
})

// 权限指令
Vue.directive('has', {
  bind: function(el, binding) {
    if (!Vue.prototype.$_has(binding.value)) {
      el.classList.add('is-disabled')  // 置灰
      el.disabled = true
      // el.parentNode.removeChild(el)  // 隐藏
    }
  }
})
// 权限检查方法
Vue.prototype.$_has = function(value) {
  // debugger
  let isExist=false
  let buttonpermsStr = getPageAction()
  if(buttonpermsStr===undefined || buttonpermsStr===null){
    return false
  }
  let buttonperms=JSON.parse(buttonpermsStr)
  for(let i=0;i<buttonperms.length;i++){
    if(buttonperms[i].code.indexOf(value)>-1){
      isExist=true
      break
    }
  }
  return isExist
}

new Vue({
  el: '#app',
  router,
  store,
  i18n,
  template: '<App/>',
  components: { App }
})
